package com.pdd.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pdd.mall.dto.PromotionParam;
import com.pdd.mall.entity.Product;
import com.pdd.mall.entity.Promotion;
import com.pdd.mall.entity.PromotionProduct;
import com.pdd.mall.mapper.ProductMapper;
import com.pdd.mall.mapper.PromotionMapper;
import com.pdd.mall.mapper.PromotionProductMapper;
import com.pdd.mall.service.PromotionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 促销活动服务实现类
 */
@Service
public class PromotionServiceImpl implements PromotionService {

    @Autowired
    private PromotionMapper promotionMapper;

    @Autowired
    private PromotionProductMapper promotionProductMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Page<Promotion> getPromotionList(Long merchantId, String keyword, String type, Integer status, String startTime, String endTime, Integer pageNum, Integer pageSize) {
        System.out.println("查询促销活动列表 - 商家ID: " + merchantId + ", 关键词: " + keyword + ", 类型: " + type +
                           ", 状态: " + status + ", 开始时间: " + startTime + ", 结束时间: " + endTime);

        Page<Promotion> page = new Page<>(pageNum, pageSize);

        QueryWrapper<Promotion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchant_id", merchantId);

        // 关键字搜索
        if (StringUtils.hasText(keyword)) {
            queryWrapper.and(wrapper -> wrapper.like("name", keyword).or().like("description", keyword));
        }

        // 类型筛选
        if (StringUtils.hasText(type)) {
            queryWrapper.eq("type", type);
        }

        // 状态筛选
        if (status != null) {
            queryWrapper.eq("status", status);
        }

        // 时间范围筛选
        if (StringUtils.hasText(startTime)) {
            queryWrapper.ge("start_time", startTime);
        }

        if (StringUtils.hasText(endTime)) {
            queryWrapper.le("end_time", endTime);
        }

        queryWrapper.orderByDesc("create_time");

        System.out.println("执行SQL查询: " + queryWrapper.getSqlSegment());

        // 检查数据库中是否有促销活动数据
        Long count = promotionMapper.selectCount(null);
        System.out.println("数据库中促销活动总数: " + count);

        Page<Promotion> result = promotionMapper.selectPage(page, queryWrapper);
        System.out.println("查询结果: 总记录数=" + result.getTotal() + ", 当前页记录数=" + result.getRecords().size());

        // 打印查询到的促销活动信息
        if (result.getRecords().size() > 0) {
            System.out.println("查询到的促销活动列表:");
            for (Promotion promotion : result.getRecords()) {
                System.out.println("  活动ID: " + promotion.getId() + ", 名称: " + promotion.getName() +
                                  ", 商家ID: " + promotion.getMerchantId() + ", 状态: " + promotion.getStatus() +
                                  ", 类型: " + promotion.getType());
            }
        } else {
            System.out.println("未查询到任何促销活动");
        }

        return result;
    }

    @Override
    public Promotion getPromotionDetail(Long id, Long merchantId) {
        QueryWrapper<Promotion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        queryWrapper.eq("merchant_id", merchantId);
        return promotionMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional
    public Promotion addPromotion(PromotionParam param, Long merchantId) {
        Promotion promotion = new Promotion();
        BeanUtils.copyProperties(param, promotion);
        promotion.setMerchantId(merchantId);

        // 设置默认的开始时间和结束时间
        LocalDateTime now = LocalDateTime.now();
        promotion.setStartTime(now);
        promotion.setEndTime(now.plusDays(30)); // 默认30天后结束

        // 使用前端传递的状态
        // 状态已经在param中设置，通过BeanUtils.copyProperties复制到promotion对象

        promotionMapper.insert(promotion);

        // 保存关联的商品
        savePromotionProducts(promotion.getId(), param.getProductIds());

        return promotion;
    }

    @Override
    @Transactional
    public Promotion updatePromotion(Long id, PromotionParam param, Long merchantId) {
        Promotion promotion = getPromotionDetail(id, merchantId);
        if (promotion == null) {
            return null;
        }

        // 保存原有的时间设置
        LocalDateTime startTime = promotion.getStartTime();
        LocalDateTime endTime = promotion.getEndTime();

        // 复制参数
        BeanUtils.copyProperties(param, promotion);

        // 恢复时间设置
        promotion.setStartTime(startTime);
        promotion.setEndTime(endTime);

        // 使用前端传递的状态
        // 状态已经在param中设置，通过BeanUtils.copyProperties复制到promotion对象

        promotionMapper.updateById(promotion);

        // 更新关联的商品
        updatePromotionProducts(promotion.getId(), param.getProductIds());

        return promotion;
    }

    @Override
    @Transactional
    public boolean deletePromotion(Long id, Long merchantId) {
        // 删除促销活动
        QueryWrapper<Promotion> promotionQueryWrapper = new QueryWrapper<>();
        promotionQueryWrapper.eq("id", id);
        promotionQueryWrapper.eq("merchant_id", merchantId);
        int count = promotionMapper.delete(promotionQueryWrapper);

        if (count > 0) {
            // 删除关联的商品
            QueryWrapper<PromotionProduct> productQueryWrapper = new QueryWrapper<>();
            productQueryWrapper.eq("promotion_id", id);
            promotionProductMapper.delete(productQueryWrapper);
            return true;
        }

        return false;
    }

    @Override
    public List<Long> getPromotionProductIds(Long promotionId) {
        QueryWrapper<PromotionProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("promotion_id", promotionId);
        queryWrapper.select("product_id");

        List<PromotionProduct> promotionProducts = promotionProductMapper.selectList(queryWrapper);
        return promotionProducts.stream().map(PromotionProduct::getProductId).collect(Collectors.toList());
    }

    @Override
    public boolean updatePromotionStatus(Long id, Integer status, Long merchantId) {
        Promotion promotion = getPromotionDetail(id, merchantId);
        if (promotion == null) {
            return false;
        }

        promotion.setStatus(status);
        return promotionMapper.updateById(promotion) > 0;
    }

    /**
     * 保存促销活动关联的商品
     */
    private void savePromotionProducts(Long promotionId, List<Long> productIds) {
        if (productIds == null || productIds.isEmpty()) {
            return;
        }

        List<PromotionProduct> promotionProducts = new ArrayList<>();
        for (Long productId : productIds) {
            PromotionProduct promotionProduct = new PromotionProduct();
            promotionProduct.setPromotionId(promotionId);
            promotionProduct.setProductId(productId);
            promotionProducts.add(promotionProduct);
        }

        for (PromotionProduct promotionProduct : promotionProducts) {
            promotionProductMapper.insert(promotionProduct);
        }
    }

    /**
     * 更新促销活动关联的商品
     */
    private void updatePromotionProducts(Long promotionId, List<Long> productIds) {
        // 删除原有关联
        QueryWrapper<PromotionProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("promotion_id", promotionId);
        promotionProductMapper.delete(queryWrapper);

        // 保存新的关联
        savePromotionProducts(promotionId, productIds);
    }

    @Override
    public Map<String, Object> getProductPromotion(Long productId) {
        Map<String, Object> result = new HashMap<>();

        System.out.println("获取商品ID: " + productId + " 的促销信息");

        // 查找与该商品关联的所有促销活动
        QueryWrapper<PromotionProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        List<PromotionProduct> promotionProducts = promotionProductMapper.selectList(queryWrapper);

        System.out.println("找到 " + promotionProducts.size() + " 个关联的促销活动");

        if (promotionProducts.isEmpty()) {
            // 没有促销活动
            result.put("hasPromotion", false);
            return result;
        }

        // 获取所有促销活动ID
        List<Long> promotionIds = promotionProducts.stream()
                .map(PromotionProduct::getPromotionId)
                .collect(Collectors.toList());

        System.out.println("促销活动ID列表: " + promotionIds);

        // 查询进行中的促销活动
        QueryWrapper<Promotion> promotionQueryWrapper = new QueryWrapper<>();
        promotionQueryWrapper.in("id", promotionIds);
        promotionQueryWrapper.eq("status", 1); // 进行中的活动

        List<Promotion> activePromotions = promotionMapper.selectList(promotionQueryWrapper);

        System.out.println("找到 " + activePromotions.size() + " 个进行中的促销活动");

        if (activePromotions.isEmpty()) {
            // 没有进行中的促销活动
            result.put("hasPromotion", false);
            return result;
        }

        // 找出最优惠的促销活动（这里简单处理，实际可能需要更复杂的逻辑）
        // 优先选择秒杀活动，其次是折扣活动，最后是满减活动
        Promotion bestPromotion = null;

        // 首先查找秒杀活动
        for (Promotion promotion : activePromotions) {
            if ("flash".equals(promotion.getType())) {
                bestPromotion = promotion;
                System.out.println("找到秒杀活动: ID=" + promotion.getId() + ", 名称=" + promotion.getName());
                break;
            }
        }

        // 如果没有秒杀活动，查找折扣活动
        if (bestPromotion == null) {
            for (Promotion promotion : activePromotions) {
                if ("percent".equals(promotion.getType())) {
                    bestPromotion = promotion;
                    System.out.println("找到折扣活动: ID=" + promotion.getId() + ", 名称=" + promotion.getName());
                    break;
                }
            }
        }

        // 如果没有折扣活动，使用第一个活动（可能是满减活动）
        if (bestPromotion == null) {
            bestPromotion = activePromotions.get(0);
            System.out.println("使用默认活动: ID=" + bestPromotion.getId() + ", 名称=" + bestPromotion.getName() + ", 类型=" + bestPromotion.getType());
        }

        result.put("hasPromotion", true);
        result.put("promotion", bestPromotion);

        System.out.println("返回的促销活动: ID=" + bestPromotion.getId() + ", 名称=" + bestPromotion.getName() +
                          ", 类型=" + bestPromotion.getType() + ", 规则=" + bestPromotion.getRules());

        return result;
    }

    @Override
    public BigDecimal calculatePromotionPrice(Long productId, BigDecimal originalPrice) {
        // 获取商品的促销信息
        Map<String, Object> promotionInfo = getProductPromotion(productId);

        if (!(Boolean) promotionInfo.get("hasPromotion")) {
            // 没有促销活动，返回原价
            return originalPrice;
        }

        Promotion promotion = (Promotion) promotionInfo.get("promotion");
        String type = promotion.getType();
        String rulesJson = promotion.getRules();

        try {
            // 解析促销规则
            Map<String, Object> rules = parseRules(rulesJson);

            // 根据促销类型计算价格
            if ("discount".equals(type)) {
                // 满减活动 - 注意：满减活动应该在订单级别应用，而不是商品级别
                // 这里我们不对单个商品应用满减，而是在OrderServiceImpl中处理
                // 但是我们仍然需要返回原价，以便在OrderServiceImpl中正确计算订单总价
                return originalPrice;
            } else if ("percent".equals(type)) {
                // 折扣活动
                BigDecimal percent = new BigDecimal(rules.get("percent").toString());
                return originalPrice.multiply(percent).setScale(2, java.math.RoundingMode.HALF_UP);
            } else if ("flash".equals(type)) {
                // 秒杀活动
                if (rules.containsKey("price") && rules.get("price") != null) {
                    try {
                        BigDecimal flashPrice = new BigDecimal(rules.get("price").toString());
                        System.out.println("秒杀价格计算: 原价=" + originalPrice + ", 秒杀价=" + flashPrice);
                        return flashPrice;
                    } catch (Exception e) {
                        System.err.println("解析秒杀价格出错: " + e.getMessage() + ", 价格值: " + rules.get("price"));
                        return originalPrice;
                    }
                } else {
                    System.err.println("秒杀规则中没有price字段或price为null: " + rules);
                    return originalPrice;
                }
            }
        } catch (Exception e) {
            System.err.println("计算促销价格出错: " + e.getMessage());
        }

        // 默认返回原价
        return originalPrice;
    }

    @Override
    public BigDecimal calculateOrderDiscount(Long productId, int quantity, BigDecimal originalPrice) {
        BigDecimal totalOriginalPrice = originalPrice.multiply(new BigDecimal(quantity));
        BigDecimal promotionPrice = calculatePromotionPrice(productId, originalPrice).multiply(new BigDecimal(quantity));

        // 折扣金额 = 原价总额 - 促销价总额
        return totalOriginalPrice.subtract(promotionPrice);
    }

    /**
     * 解析促销规则JSON
     */
    private Map<String, Object> parseRules(String rulesJson) {
        Map<String, Object> rules = new HashMap<>();

        if (rulesJson == null || rulesJson.trim().isEmpty()) {
            System.err.println("促销规则为空");
            return rules;
        }

        try {
            // 使用Jackson库解析JSON
            ObjectMapper objectMapper = new ObjectMapper();
            @SuppressWarnings("unchecked")
            Map<String, Object> result = objectMapper.readValue(rulesJson, Map.class);
            return result;
        } catch (Exception e) {
            System.err.println("使用Jackson解析JSON失败，尝试手动解析: " + e.getMessage());

            // 备用的手动解析方法
            try {
                // 简单解析，实际应该使用JSON库
                rulesJson = rulesJson.replace("{", "").replace("}", "").replace("\"", "");
                String[] pairs = rulesJson.split(",");

                for (String pair : pairs) {
                    String[] keyValue = pair.split(":");
                    if (keyValue.length == 2) {
                        String key = keyValue[0].trim();
                        String value = keyValue[1].trim();

                        // 尝试转换为数字
                        try {
                            if (value.contains(".")) {
                                rules.put(key, Double.parseDouble(value));
                            } else {
                                rules.put(key, Integer.parseInt(value));
                            }
                        } catch (NumberFormatException ex) {
                            rules.put(key, value);
                        }
                    }
                }
            } catch (Exception ex) {
                System.err.println("手动解析JSON也失败: " + ex.getMessage());
                System.err.println("原始JSON字符串: " + rulesJson);
            }
        }

        return rules;
    }

    @Override
    public List<Promotion> getActivePromotions() {
        System.out.println("获取所有进行中的促销活动");

        // 查询所有进行中的促销活动
        QueryWrapper<Promotion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1); // 进行中的活动
        queryWrapper.orderByDesc("create_time");

        List<Promotion> activePromotions = promotionMapper.selectList(queryWrapper);
        System.out.println("查询到" + activePromotions.size() + "个进行中的促销活动");

        if (activePromotions.isEmpty()) {
            return activePromotions;
        }

        // 过滤出有关联商品的促销活动
        List<Promotion> result = new ArrayList<>();
        for (Promotion promotion : activePromotions) {
            // 获取促销活动关联的商品ID列表
            List<Long> productIds = getPromotionProductIds(promotion.getId());
            if (!productIds.isEmpty()) {
                result.add(promotion);
                System.out.println("促销活动ID: " + promotion.getId() + ", 名称: " + promotion.getName() +
                                  ", 关联商品数: " + productIds.size());
            } else {
                System.out.println("促销活动ID: " + promotion.getId() + ", 名称: " + promotion.getName() +
                                  " 没有关联商品，不返回给用户端");
            }
        }

        System.out.println("最终返回" + result.size() + "个有效的促销活动");
        return result;
    }

    @Override
    @Transactional
    public int updateProductPricesByPromotion(Long promotionId, boolean isStart) {
        System.out.println("更新促销活动ID: " + promotionId + " 关联商品的价格, isStart=" + isStart);

        // 获取促销活动详情
        Promotion promotion = promotionMapper.selectById(promotionId);
        if (promotion == null) {
            System.err.println("促销活动不存在: " + promotionId);
            return 0;
        }

        // 获取促销活动关联的商品ID列表
        List<Long> productIds = getPromotionProductIds(promotionId);
        if (productIds.isEmpty()) {
            System.out.println("促销活动没有关联商品");
            return 0;
        }

        System.out.println("促销活动关联的商品数量: " + productIds.size());

        int updatedCount = 0;

        // 遍历商品，更新价格
        for (Long productId : productIds) {
            Product product = productMapper.selectById(productId);
            if (product == null) {
                System.err.println("商品不存在: " + productId);
                continue;
            }

            if (isStart) {
                // 促销开始，更新价格为促销价格
                // 先保存原价
                if (product.getOriginalPrice() == null) {
                    product.setOriginalPrice(product.getPrice());
                }

                // 计算促销价格
                BigDecimal promotionPrice = calculatePromotionPrice(productId, product.getOriginalPrice());

                // 如果是秒杀活动，检查价格是否正确
                if ("flash".equals(promotion.getType())) {
                    System.out.println("检测到秒杀活动，商品ID: " + productId);
                    System.out.println("原价: " + product.getOriginalPrice() + ", 计算的秒杀价格: " + promotionPrice);

                    // 解析规则，获取秒杀价格
                    try {
                        Map<String, Object> rules = parseRules(promotion.getRules());
                        if (rules.containsKey("price")) {
                            BigDecimal flashPrice = new BigDecimal(rules.get("price").toString());
                            System.out.println("规则中的秒杀价格: " + flashPrice);

                            // 使用规则中的秒杀价格
                            promotionPrice = flashPrice;
                        }
                    } catch (Exception e) {
                        System.err.println("解析秒杀规则失败: " + e.getMessage());
                    }
                }

                // 更新商品价格为促销价格
                product.setPrice(promotionPrice);

                System.out.println("商品ID: " + productId + " 价格从 " + product.getOriginalPrice() + " 更新为 " + promotionPrice);
            } else {
                // 促销结束，恢复原价
                if (product.getOriginalPrice() != null) {
                    System.out.println("商品ID: " + productId + " 价格从 " + product.getPrice() + " 恢复为 " + product.getOriginalPrice());
                    product.setPrice(product.getOriginalPrice());
                } else {
                    System.err.println("商品ID: " + productId + " 没有原价记录，无法恢复");
                }
            }

            // 更新商品
            int result = productMapper.updateById(product);
            if (result > 0) {
                updatedCount++;
            }
        }

        System.out.println("成功更新 " + updatedCount + " 个商品的价格");
        return updatedCount;
    }
}
